import os

import pygame

def load_image(path):
    """Returns pygame.Surface, pygame.Rect"""
    try:
        image = pygame.image.load(path)
        if image.get_alpha() is None:
            image = image.convert()
        else:
            image = image.convert_alpha()
    except pygame.error, message:
        print 'Cannot load image:', path
        raise SystemExit, message
    return image, image.get_rect()

def load_sound(path):
    """Return sound object from full sound path
    """
    try:
        sound = pygame.mixer.Sound(path)
    except pygame.error, message:
        print 'Cannot load sound:', path
        raise SystemExit, message
    return sound

def load_font(path):
    """Return font object from full font path
    """
    try:
        font = pygame.font.Font(path, 11)
    except pygame.error, message:
        print 'Cannot load font:', path
        raise SystemExit, message
    return font

class ResourceManager(object):
    cache = {}
    loaders = {'png': load_image,
               'ogg': load_sound,
               'ttf': load_font,
               }
    
    @classmethod
    def get(cls, name):
        if name in cls.cache:
            return cls.cache[name]
        else:
            return cls.load(name)
    
    @classmethod
    def load(cls, path, extension=None):
        if extension is None:
            extension = path.rsplit('.', 1)[-1]
        if extension in cls.loaders:
            resource = cls.loaders[extension](path)
            cls.cache[os.path.basename(path)] = resource
            return resource
        else:
            return None
    
    @classmethod
    def load_folder(cls, path):
        #TODO: implement
        pass
    
    @classmethod
    def load_folder_recursive(cls, top):
        for path, dirs, files in os.walk(top):
            for file in files:
                cls.load(os.path.join(path, file))